<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { type UserInfo } from '@/stores/user'
import { useCascaderAreaData } from '@vant/area-data'
import { addCheckPerson } from '@/api/wechat/checkperson'
import { showSuccessToast } from 'vant'
import { debounce } from '@/utils/cal'
import {
  CLASS_OPTION,
  SCHOOL_LEVEL_OPTION,
  SCHOOL_YEAR_OPTION,
  type SelectOption,
} from '@/constant/select_options'

// Hooks
const router = useRouter()
const userInfo = ref<UserInfo>({
  category: 'wx',
  address: '',
  name: '',
  cardID: '',
  sex: '',
  age: '',
  schoolLevel: '',
  schoolName: '',
  schoolID: '',
  grade: '',
  sclass: '',
  sno: '',
  accountId: '',
})

const columns = ref<SelectOption[]>([])
const show = ref(false)
const showPicker = ref(false)
const idInputDisabled = ref(false)
const isLoading = ref(false)
const sign = ref<number>(1)

// 地区数据
const options = useCascaderAreaData()

const onFinish = ({ selectedOptions }: any) => {
  userInfo.value.address = selectedOptions.map((option: any) => option.text).join(' ')
  show.value = false
}

const handleChooseAddress = () => {
  show.value = true
}
const handleChooseSchoolLevel = () => {
  columns.value = SCHOOL_LEVEL_OPTION
  sign.value = 1
  showPicker.value = true
}
const handleChooseGrade = () => {
  columns.value = SCHOOL_YEAR_OPTION
  sign.value = 2
  showPicker.value = true
}
const handleChooseClass = () => {
  columns.value = CLASS_OPTION
  sign.value = 3
  showPicker.value = true
}

// 表单提交 添加筛查人
const onSubmit = () => {
  addCheckPerson(userInfo.value).then(() => {
    showSuccessToast('添加成功')
    router.go(-1)
  })
}

// 确认选择框
const onConfirm = (value: any) => {
  const selectedValue = value.selectedValues[0]
  switch (sign.value) {
    case 1: {
      userInfo.value.schoolLevel = selectedValue
      break
    }
    case 2: {
      userInfo.value.grade = selectedValue
      break
    }
    case 3: {
      userInfo.value.sclass = selectedValue
      break
    }
  }
  showPicker.value = false
}

// 返回上级
const onClickLeft = () => {
  router.push('/')
}

// 点击选择学校
const handleSelectSchool = () => {
  router.push('/select/school')
}

// 防抖处理身份证号输入
const handleIdInput = debounce(() => {
  const cardID = userInfo.value.cardID
  if (cardID && cardID.length === 18) {
    isLoading.value = true
    // 自动填充性别和年龄
    userInfo.value.sex = parseInt(cardID[16]) % 2 === 1 ? '男' : '女'
    const birthDateStr = cardID.slice(6, 14)
    const birthYear = parseInt(birthDateStr.slice(0, 4))
    const birthMonth = parseInt(birthDateStr.slice(4, 6)) - 1
    const birthDay = parseInt(birthDateStr.slice(6, 8))
    const birthDate = new Date(birthYear, birthMonth, birthDay)
    const now = new Date()
    let age = now.getFullYear() - birthYear
    if (
      now.getMonth() < birthMonth ||
      (now.getMonth() === birthMonth && now.getDate() < birthDay)
    ) {
      age--
    }
    userInfo.value.age = age.toString()
  }
  isLoading.value = false // 停止加载
  idInputDisabled.value = false // 恢复其他输入框
}, 230)

// 监听身份证号输入框
watch(
  () => userInfo.value.cardID,
  (newCardID) => {
    if (newCardID && newCardID.length < 18) {
      idInputDisabled.value = true // 禁用其他输入框
    } else {
      idInputDisabled.value = false // 输入完成后恢复其他输入框
    }
    isLoading.value = true // 开启 loading
    handleIdInput()
  },
)
</script>

<template>
  <div>
    <van-nav-bar title="添加筛查人" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit" required="auto">
      <van-cell-group inset>
        <van-field
          v-model="userInfo.address"
          is-link
          readonly
          label="居住地"
          placeholder="选择居住地"
          @click="handleChooseAddress"
          :rules="[{ required: true, message: '请选择居住地' }]"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.name"
          name="姓名"
          label="姓名"
          placeholder="请填写筛查人姓名"
          :rules="[{ required: true, message: '请填写筛查人姓名' }]"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.cardID"
          name="身份证号"
          label="身份证号"
          placeholder="请填写身份证号"
          :rules="[
            { required: true, message: '请填写身份证号' },
            { pattern: /^(\d{18}|\d{17}X)$/, message: '请输入正确的身份证号' },
          ]"
        />
        <span class="small-tip"
          >身份证号为系统筛查唯一编码，录入错误不可更改，只能除后重新录入</span
        >
        <van-field
          v-model="userInfo.sex"
          name="性别"
          label="性别"
          placeholder="根据身份证号自动填写"
          :rules="[{ required: true, message: '根据身份证号自动填写' }]"
          disabled
          :class="isLoading ? 'loading' : ''"
        />
        <van-field
          v-model="userInfo.age"
          name="年龄"
          label="年龄"
          placeholder="根据身份证号自动填写"
          :rules="[{ required: true, message: '根据身份证号自动填写' }]"
          disabled
          :class="isLoading ? 'loading' : ''"
        />
        <van-field
          v-model="userInfo.schoolLevel"
          is-link
          readonly
          label="学段"
          placeholder="选择学段"
          @click="handleChooseSchoolLevel"
          :rules="[{ required: true, message: '请选择学段' }]"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.schoolName"
          is-link
          readonly
          label="学校"
          placeholder="选择学校"
          @click="handleSelectSchool"
          :rules="[{ required: true, message: '请选择学校' }]"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.grade"
          is-link
          readonly
          label="年级"
          placeholder="选择年级"
          @click="handleChooseGrade"
          :rules="[{ required: true, message: '请选择年级' }]"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.sclass"
          is-link
          readonly
          label="班别"
          placeholder="选择班别"
          @click="handleChooseClass"
          :disabled="idInputDisabled"
        />
        <van-field
          v-model="userInfo.sno"
          name="学号"
          label="学号"
          placeholder="请输入学号"
          :disabled="idInputDisabled"
        />

        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>

        <van-popup v-model:show="show" round position="bottom">
          <van-cascader
            title="请选择所在地区"
            :options="options"
            @close="show = false"
            @finish="onFinish"
          />
        </van-popup>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit" @click="onSubmit">
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped lang="scss">
.loading {
  position: relative;
  background-color: #f5f5f5; /* 提示背景 */
  color: #999; /* 提示文字颜色 */
}

.loading::after {
  content: '';
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top-color: #409eff; /* 指定加载动画的颜色 */
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: translateY(-50%) rotate(0deg);
  }
  to {
    transform: translateY(-50%) rotate(360deg);
  }
}

.small-tip {
  font-size: 12px;
  color: #999;
  margin: 8px 16px;
  display: block;
  text-align: left;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-all;
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
}
</style>
